import org.apache.catalina.tribes.*;
import org.apache.catalina.tribes.group.GroupChannel;

import java.io.Serializable;
import java.util.Scanner;

/**
 * Created by PPurohit on 1/5/2015.
 */
public class CommTest {

    public static void main(String[] args) throws ChannelException {
        Channel myChannel = new GroupChannel();

        //create my listeners
        ChannelListener msgListener = new MyMessageListener();
        MembershipListener mbrListener = new MyMemberListener();

        //attach the listeners to the channel
        myChannel.addMembershipListener(mbrListener);
        myChannel.addChannelListener(msgListener);

        //start the channel
        myChannel.start(Channel.DEFAULT);

        while (true) {
            Scanner kb = new Scanner(System.in);
            String line = kb.nextLine();
            if ("q".equalsIgnoreCase(line)) {
                break;
            }

            //create a message to be sent, message must implement java.io.Serializable
            //for performance reasons you probably want them to implement java.io.Externalizable
            Serializable myMsg = new MyMessage(line);

            //retrieve my current members
            Member[] group = myChannel.getMembers();
            if (null != group && group.length > 0) {
                //send the message
                myChannel.send(group, myMsg, Channel.SEND_OPTIONS_DEFAULT);
            }
        }

    }

    private static class MyMessageListener implements ChannelListener {
        @Override
        public void messageReceived(Serializable serializable, Member member) {
            System.out.printf("Message %s received from %s.", serializable, member);
        }

        @Override
        public boolean accept(Serializable serializable, Member member) {
            return true;
        }
    }

    private static class MyMessage implements Serializable {
        private final String line;

        public MyMessage(String line) {
            this.line = line;
        }

        @Override
        public String toString() {
            return "MyMessage{" +
                    "line='" + line + '\'' +
                    '}';
        }
    }

    private static class MyMemberListener implements MembershipListener {
        @Override
        public void memberAdded(Member member) {
            System.out.printf("New member %s joined.", member);
        }

        @Override
        public void memberDisappeared(Member member) {
            System.out.printf("New member %s disappeared.", member);
        }
    }
}
